/*
 * OptionPanel.java
 *
 * Created on 2008年6月7日, 下午2:56
 */

package gui;
import java.awt.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.tree.*;
import java.io.*;
import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.table.*;
import java.util.*;
import java.text.*;
import abstractmodel.*;
import model.Book;

/**
 *
 * @author  yux
 */
public class OptionPanel extends javax.swing.JPanel {
    public static DefaultTreeModel setTreeModel;
    public static DefaultMutableTreeNode setRoot;
    public static DefaultMutableTreeNode userInfo;
    public static DefaultMutableTreeNode[] accountInfo;
    public static DefaultMutableTreeNode skin;
    private IUser ur;
    private String status;
    private String store;
    private MainFrame mf;
    
    private UIManager.LookAndFeelInfo[] lookfeels=new UIManager.LookAndFeelInfo[16];
    private ButtonGroup jbg=new ButtonGroup();
    /** Creates new form OptionPanel */
    public OptionPanel(MainFrame m, IUser u) {
        mf = m;
        ur = u;
        initComponents();
        jPanelSetInfo.setLayout(new java.awt.BorderLayout());
        jTree1.setModel(initjTreeSet());
        initSkin();
        status = "user";
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jTabbedPaneInfo = new javax.swing.JTabbedPane();
        jPanelUser = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTree1 = new javax.swing.JTree();
        jScrollPane2 = new javax.swing.JScrollPane();
        jPanelSetInfo = new javax.swing.JPanel();
        jPanelSkin = new javax.swing.JPanel();
        jButtonConfirm = new javax.swing.JButton();
        jButtonClose = new javax.swing.JButton();
        jLabelSet = new javax.swing.JLabel();

        jTabbedPaneInfo.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                jTabbedPaneInfoStateChanged(evt);
            }
        });

        jTree1.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                jTree1ValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(jTree1);

        javax.swing.GroupLayout jPanelSetInfoLayout = new javax.swing.GroupLayout(jPanelSetInfo);
        jPanelSetInfo.setLayout(jPanelSetInfoLayout);
        jPanelSetInfoLayout.setHorizontalGroup(
            jPanelSetInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 409, Short.MAX_VALUE)
        );
        jPanelSetInfoLayout.setVerticalGroup(
            jPanelSetInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 414, Short.MAX_VALUE)
        );

        jScrollPane2.setViewportView(jPanelSetInfo);

        javax.swing.GroupLayout jPanelUserLayout = new javax.swing.GroupLayout(jPanelUser);
        jPanelUser.setLayout(jPanelUserLayout);
        jPanelUserLayout.setHorizontalGroup(
            jPanelUserLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelUserLayout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 411, Short.MAX_VALUE))
        );
        jPanelUserLayout.setVerticalGroup(
            jPanelUserLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 416, Short.MAX_VALUE)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 416, Short.MAX_VALUE)
        );

        jTabbedPaneInfo.addTab("\u7528\u6237\u4fe1\u606f", jPanelUser);

        javax.swing.GroupLayout jPanelSkinLayout = new javax.swing.GroupLayout(jPanelSkin);
        jPanelSkin.setLayout(jPanelSkinLayout);
        jPanelSkinLayout.setHorizontalGroup(
            jPanelSkinLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 574, Short.MAX_VALUE)
        );
        jPanelSkinLayout.setVerticalGroup(
            jPanelSkinLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 416, Short.MAX_VALUE)
        );

        jTabbedPaneInfo.addTab("\u76ae\u80a4\u8bbe\u7f6e", jPanelSkin);

        jButtonConfirm.setText("确定"); // NOI18N
        jButtonConfirm.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonConfirmActionPerformed(evt);
            }
        });

        jButtonClose.setText("关闭"); // NOI18N
        jButtonClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCloseActionPerformed(evt);
            }
        });

        jLabelSet.setText("用户信息设置"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPaneInfo, javax.swing.GroupLayout.DEFAULT_SIZE, 579, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(41, 41, 41)
                .addComponent(jLabelSet)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 316, Short.MAX_VALUE)
                .addComponent(jButtonConfirm, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButtonClose, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jTabbedPaneInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 444, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelSet)
                    .addComponent(jButtonClose)
                    .addComponent(jButtonConfirm))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void initSkin() {
        for(int i=0;i!=lookfeels.length;++i) {
            lookfeels[i]=UIManager.getInstalledLookAndFeels()[i+4];
        }
        this.jPanelSkin.setLayout(new java.awt.GridLayout(lookfeels.length/2,2));
        for(int i=0;i!=2*(lookfeels.length/2);++i) {
            DisplayRadioButton drb=new DisplayRadioButton(lookfeels[i]);
            drb.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    class TmpRun implements Runnable {
                        DisplayRadioButton b;
                        TmpRun(DisplayRadioButton rb) {
                            b=rb;
                        }
                        public void run() {
                            try {
                                UIManager.setLookAndFeel(b.getLookFeelInfo().getClassName());
                                SwingUtilities.updateComponentTreeUI(OptionPanel.this);
                            } catch (ClassNotFoundException ex) {
                                Logger.getLogger(OptionPanel.class.getName()).log(Level.SEVERE, null, ex);
                            } catch (InstantiationException ex) {
                                Logger.getLogger(OptionPanel.class.getName()).log(Level.SEVERE, null, ex);
                            } catch (IllegalAccessException ex) {
                                Logger.getLogger(OptionPanel.class.getName()).log(Level.SEVERE, null, ex);
                            } catch (UnsupportedLookAndFeelException ex) {
                                Logger.getLogger(OptionPanel.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }       
                    }
                    SwingUtilities.invokeLater(new TmpRun((DisplayRadioButton)e.getSource()));
                }
            });
            jbg.add(drb);
            this.jPanelSkin.add(drb);
        }
    }

    private void jTabbedPaneInfoStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jTabbedPaneInfoStateChanged
        // TODO add your handling code here:
        int index = this.jTabbedPaneInfo.getSelectedIndex();
        System.out.println("index:"+index);
        if (index == 1) {
            store = status;
            status = "skin";
            this.jLabelSet.setText("界面皮肤设置");
        }else {
            status = store;
            this.jLabelSet.setText("用户信息设置");
        }
    }//GEN-LAST:event_jTabbedPaneInfoStateChanged

    private void jButtonConfirmActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonConfirmActionPerformed
        // TODO add your handling code here:
        change();
        Utilities.cancelDialog(this);
    }//GEN-LAST:event_jButtonConfirmActionPerformed

    private void jButtonCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCloseActionPerformed
        // TODO add your handling code here:
        Utilities.cancelDialog(this);
    }//GEN-LAST:event_jButtonCloseActionPerformed

    private void jTree1ValueChanged(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_jTree1ValueChanged
        // TODO add your handling code here:
        TreePath path = evt.getPath();
        String name = path.getLastPathComponent().toString();
        Object o = searchNode(name);
        if(o == null)
            return;
        System.out.println("option-name:"+name);
        if(status.equals("user")) {
            jPanelSetInfo.removeAll();
            jPanelSetInfo.add(new OptionUserPanel(mf, (model.User)o), BorderLayout.CENTER);            
        }else if(status.equals("book")) {
            jPanelSetInfo.removeAll();
            Book newBook = (Book)o;
            jPanelSetInfo.add(new OptionBookPanel(mf, (model.Book)newBook), BorderLayout.CENTER);
        }else if(status.contains("account")) {
            jPanelSetInfo.removeAll();
            IAccount account = (IAccount)o;
            if(account.getAccountInfo().getType() == configure.Global.BANK_ACCOUNT_INFO_TYPE)
                jPanelSetInfo.add(new OptionDebitPanel(mf, account), BorderLayout.CENTER);
            else if(account.getAccountInfo().getType() == configure.Global.CREDITCARD_ACCOUNT_INFO_TYPE)
                jPanelSetInfo.add(new gui.OptionCreditPanel(mf, account), BorderLayout.CENTER);
            else {
                jPanelSetInfo.add(new gui.OptionMoneyPanel(mf, account), BorderLayout.CENTER);
            }                     
        }
        this.updateUI();
    }//GEN-LAST:event_jTree1ValueChanged
    
    private Object searchNode(String name) {
        if (name.equals("基本信息")) {
            status = "user";
            return ur;
        }
        int size = ur.getBooks().size();
        for(int i = 0; i < size; i++) {
            IBook book = ur.getBooks().get(i);
            if(book.getBookInfo().getValue("账簿名称").toString().equals(name)) {
                status = "book";
                return book;
            }
            int length = book.getAccounts().size();
            for(int j = 0; j < length; j++) 
                if (book.getAccounts().get(j).getAccountInfo().getValue("帐户名称").
                toString().equals(name)) {
                    if(book.getAccounts().get(j).getAccountInfo().getType() == 
                            configure.Global.BANK_ACCOUNT_INFO_TYPE)
                        status = "bank_account";
                    else if(book.getAccounts().get(j).getAccountInfo().getType() == 
                            configure.Global.MONEY_ACCOUNT_INFO_TYPE)
                        status = "money_account";
                    else
                        status = "credit_account";
                    return book.getAccounts().get(j);
                }
        }
        return null;
    }
    
     /**
     * 如果用户点击确定或应用按钮，则将写入的信息存储
     */
    private void change() {
        System.out.println("here");
        if(status.equals("skin")) {
            
        }else if(status.equals("user")){
            //"密码", "客户姓名"", "性别", "联系电话"
            System.out.println("here2");
            gui.OptionUserPanel p = (gui.OptionUserPanel)jPanelSetInfo.getComponent(0);
            String s[] = p.returnValue();
            IInfo info=ur.getUserInfo();
            if(s.length == 4) {
                System.out.println("option-user:"+s.length+s[0]);
                info.setValue("密码", s[0]);
                info.setValue("客户姓名", s[1]);
                info.setValue("性别", s[2]);
                info.setValue("联系电话", s[3]);
            }else {
                System.out.println("option-user:"+s.length+s[1]);
                info.setValue("客户姓名", s[0]);
                info.setValue("性别", s[1]);
                info.setValue("联系电话", s[2]);
            }
            ur.setUserInfo(info);
        }else if(status.equals("book")) {
            OptionBookPanel p = (gui.OptionBookPanel)jPanelSetInfo.getComponent(0);
            String s[] = p.returnValue();
            String name = (String)((DefaultMutableTreeNode)jTree1.getSelectionPath().getLastPathComponent()).getUserObject();
            System.out.println(name);
            IBook book = (Book)searchNode(name);
            IInfo info=book.getBookInfo();
            info.setValue("账簿名称", s[0]);
            info.setValue("备注", s[1]);
            book.setBookInfo(info);
        }else if(status.equals("bank_account")) {
            gui.OptionDebitPanel p = (gui.OptionDebitPanel)jPanelSetInfo.getComponent(0);
            String s[] = p.returnValue();
            String name = (String)((DefaultMutableTreeNode)jTree1.getSelectionPath().getLastPathComponent()).getUserObject();
            System.out.println(name);
            IAccount account = (model.BankAccount)searchNode(name);
            //"帐户名称", "归属银行", "卡号", "开户名", "开户日期", "类型"
            IInfo info=account.getAccountInfo();
            info.setValue("帐户名称", s[0]);
            info.setValue("归属银行", s[1]);
            info.setValue("卡号", s[2]);
            info.setValue("开户名", s[3]);
            info.setValue("开户日期", s[4]);
            info.setValue("类型", s[5]);
        }else if(status.equals("money_account")) {
            gui.OptionMoneyPanel p = (gui.OptionMoneyPanel)jPanelSetInfo.getComponent(0);
            String s[] = p.returnValue();
            String name = (String)((DefaultMutableTreeNode)jTree1.getSelectionPath().getLastPathComponent()).getUserObject();
            System.out.println(name);
            IAccount account = (model.Account)searchNode(name);
            //"帐户名称", "归属银行", "卡号", "开户名", "开户日期", "类型"
            IInfo info=account.getAccountInfo();
            info.setValue("帐户名称", s[0]);
        }else if(status.equals("credit_account")) {
            //"帐户名称", "归属银行", "卡号", "开户名", "额度", "有效日期", "还款日期", "帐单日"
            gui.OptionCreditPanel p = (gui.OptionCreditPanel)jPanelSetInfo.getComponent(0);
            String s[] = p.returnValue();
            String name = (String)((DefaultMutableTreeNode)jTree1.getSelectionPath().getLastPathComponent()).getUserObject();
            System.out.println(name);
            IAccount account = (model.CreditCardAccount)searchNode(name);
            IInfo info=account.getAccountInfo();
            info.setValue("帐户名称", s[0]);
            info.setValue("归属银行", s[1]);
            info.setValue("卡号", s[2]);
            info.setValue("开户名", s[3]);
            info.setValue("额度", s[4]);
            info.setValue("有效日期", s[5]);
            info.setValue("还款日期", s[6]);
            info.setValue("帐单日", s[7]);
            account.setAccountInfo(info);
        }
        refreshTree();
    }
    
    private DefaultTreeModel initjTreeSet() {
        setRoot = new DefaultMutableTreeNode("设置");
        userInfo = new DefaultMutableTreeNode("基本信息");
        int size = ur.getBooks().size();
        setRoot.add(userInfo);
        for(int i = 0; i < size; i++) {
            IBook book = ur.getBooks().get(i);
            DefaultMutableTreeNode node = new 
                    DefaultMutableTreeNode(book.getBookInfo().getValue("账簿名称").getString());
            int length = book.getAccounts().size();
            for(int j = 0; j < length; j++) 
                node.add(new DefaultMutableTreeNode
                        (book.getAccounts().get(j).getAccountInfo().getValue("帐户名称").getString()));
            setRoot.add(node);
        }
        setTreeModel = new DefaultTreeModel(setRoot,true);
        return setTreeModel;
    }
    private void refreshTree() {
        initjTreeSet();
        Main.frame.freshjTreeSystem();
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton jButtonClose;
    private javax.swing.JButton jButtonConfirm;
    private javax.swing.JLabel jLabelSet;
    private javax.swing.JPanel jPanelSetInfo;
    private javax.swing.JPanel jPanelSkin;
    private javax.swing.JPanel jPanelUser;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTabbedPane jTabbedPaneInfo;
    private javax.swing.JTree jTree1;
    // End of variables declaration//GEN-END:variables
    
}
class DisplayRadioButton extends JRadioButton {
    UIManager.LookAndFeelInfo lookfeel;
    public DisplayRadioButton(UIManager.LookAndFeelInfo info) {
        super(info.getName());
        lookfeel=info;
    }
    UIManager.LookAndFeelInfo getLookFeelInfo() {
        return lookfeel;
    }
}